package com.yami.shop.distribution.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.distribution.common.dto.DistributionUserAchievementDataDto;
import com.yami.shop.distribution.common.model.DistributionUser;
import com.yami.shop.distribution.common.param.RangeTimeParam;
import com.yami.shop.distribution.common.param.UpdateDistributionUserParam;
import com.yami.shop.distribution.common.service.DistributionUserService;
import com.yami.shop.distribution.common.vo.DistributionUserVO;
import com.yami.shop.security.platform.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yami.shop.common.util.BeanUtil;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * @author lgh on 2019/04/01.
 */
@RestController
@RequestMapping("/distribution/distributionUser")
@Tag(name = "平台端分销员接口")
public class DistributionUserController {

    @Autowired
    private DistributionUserService distributionUserService;


    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('distribution:distributionUser:page')")
    @Operation(summary =  "分页查看分销员信息")
    @Parameters({
            @Parameter(name = "userMobile", description = "分销员手机号码"),
            @Parameter(name = "parentUserMobile", description = "上级分销员手机号码")
    })
    public ServerResponseEntity<IPage<DistributionUser>> page(@ParameterObject DistributionUser distributionUser, RangeTimeParam rangeTimeParam,
                                                              String userMobile, String parentUserMobile, Integer state, PageParam<DistributionUser> page) {
        IPage<DistributionUser> list = distributionUserService.distributionUserPage(page, distributionUser, rangeTimeParam, userMobile, parentUserMobile, 0, state);
        return ServerResponseEntity.success(list);
    }

    @GetMapping("/info/achievementData/{id}")
    @PreAuthorize("@pms.hasPermission('distribution:distributionUser:info')")
    @Operation(summary =  "获取分销员与等级条件匹配的数据")
    @Parameter(name = "id", description = "分销员id")
    public ServerResponseEntity<DistributionUserAchievementDataDto> getDistributionUserAchievementData(@PathVariable("id") Long id) {
        return ServerResponseEntity.success(distributionUserService.getDistributionUserLevelAchievementDataByDistributionUserId(id));
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("@pms.hasPermission('distribution:distributionUser:info')")
    @Operation(summary =  "获取分销员信息")
    @Parameter(name = "id", description = "分销员id")
    public ServerResponseEntity<DistributionUser> info(@PathVariable("id") Long id) {
        DistributionUser distributionUser = distributionUserService.getById(id);
        return ServerResponseEntity.success(distributionUser);
    }

    @GetMapping("/page/achievement")
    @PreAuthorize("@pms.hasPermission('distribution:distributionUser:page')")
    @Operation(summary =  "获取分销员业绩")
    @Parameter(name = "userMobile", description = "分销员手机号码")
    public ServerResponseEntity<IPage<DistributionUser>> page(@ParameterObject DistributionUser distributionUser, String userMobile,
                                                        PageParam<DistributionUser> page) {
        distributionUser.setShopId(Constant.PLATFORM_SHOP_ID);
        IPage<DistributionUser> list = distributionUserService.getDistributionUserAchievementPage(page, distributionUser, userMobile);
        return ServerResponseEntity.success(list);
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('distribution:distributionUser:save')")
    @Operation(summary =  "保存分销员信息")
    public ServerResponseEntity<Void> save(@RequestBody @Valid DistributionUser distributionUser) {
        distributionUserService.save(distributionUser);
        return ServerResponseEntity.success();
    }

    @PutMapping
    @PreAuthorize("@pms.hasPermission('distribution:distributionUser:update')")
    @Operation(summary =  "修改分销员信息")
    public ServerResponseEntity<Void> update(@RequestBody @Valid DistributionUser distributionUser) {
        distributionUserService.updateById(distributionUser);
        return ServerResponseEntity.success();
    }

    @PutMapping("/state")
    @PreAuthorize("@pms.hasPermission('distribution:distributionUser:update')")
    @Operation(summary =  "修改分销员状态")
    public ServerResponseEntity<Void> update(@RequestBody UpdateDistributionUserParam param) {
        Integer disState = param.getState();
//        if(disState==1){
//            DistributionUser exitDistributionUser = distributionUserService.getById(param.getDistributionUserId());
//            Integer exitState =exitDistributionUser.getState();
//            if(exitState==1){
//                throw new YamiShopBindException("yami.distribution.has.distributionUser");
//            }
//        }
        distributionUserService.updateSelectiveAndInsertDistributionUserBan(param, SecurityUtils.getSysUser().getUserId());
        DistributionUser dbDistributionUser = distributionUserService.getById(param.getDistributionUserId());
        distributionUserService.removeCacheByUserIdAndShopId(dbDistributionUser.getUserId(), dbDistributionUser.getShopId());
        distributionUserService.removeCacheByCardNo(dbDistributionUser.getCardNo());
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('distribution:distributionUser:delete')")
    @Operation(summary =  "根据分销员id批量删除分销员信息")
    @Parameter(name = "ids", description = "分销员id")
    public ServerResponseEntity<Void> delete(@RequestBody List<Long> ids) {
        distributionUserService.removeByIds(ids);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getInfo/{userId}")
    @Operation(summary =  "根据用户id获取分销员信息")
    @Parameter(name = "userId", description = "用户id")
    public ServerResponseEntity<DistributionUser> getInfo(@PathVariable("userId") String userId) {
        DistributionUser distributionUser = distributionUserService.getByUserIdAndShopId(userId, Constant.PLATFORM_SHOP_ID);
        if (Objects.isNull(distributionUser)) {
            return ServerResponseEntity.success(distributionUser);
        }
        if (Objects.nonNull(distributionUser.getParentId())) {
            DistributionUser parentUser = distributionUserService.getById(distributionUser.getParentId());
            distributionUser.setParentDistributionUser(BeanUtil.map(parentUser, DistributionUserVO.class));
        }
        return ServerResponseEntity.success(distributionUser);
    }
}
